package cn.lg.soar.mvc.config;

import cn.lg.soar.common.model.HttpResult;
import cn.lg.soar.common.util.data.DataUtil;
import cn.lg.soar.mvc.enums.PathFilterModeEnum;
import cn.lg.soar.mvc.model.PathFilterProperties;
import cn.lg.soar.mvc.util.ResponseUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.annotation.Order;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Set;

/**
 * 路径过滤
 * @author luguoxiang
 */
@Order(0)
@Configuration
public class PathFilterInterceptor implements WebMvcConfigurer {

    protected static final Logger LOGGER = LoggerFactory.getLogger(PathFilterInterceptor.class);
    @Autowired
    private PathFilterProperties props;

    @Override
    public void addInterceptors(InterceptorRegistry registry) {

        Set<String> paths = props.getPaths();
        if (DataUtil.isValuable(paths)) {
            if (PathFilterModeEnum.blacklist.equals(props.getMode())) {
                registry.addInterceptor(new InnerInterceptor(props.getMessage()))
                        .addPathPatterns(paths.toArray(new String[0]))
                        .order(0);
            } else {
                registry.addInterceptor(new InnerInterceptor(props.getMessage()))
                        .excludePathPatterns(paths.toArray(new String[0]))
                        .order(0);
            }
        }
    }

    /**
     * 白名单拦截器
     */
    public static class InnerInterceptor implements HandlerInterceptor {

        private final String message;

        public InnerInterceptor(String message) {
            this.message = message;
        }

        @Override
        public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
            LOGGER.warn("请求拦截拦截，path={}", request.getServletPath());
            response.setStatus(412);
            ResponseUtils.responseBody(response, HttpResult.fail("B0412", message));
            return false;
        }

    }

}
